package com.itheima.health.controller;

import com.itheima.health.common.MessageConst;
import com.itheima.health.entity.Result;
import com.itheima.health.exception.BusinessRuntimeException;
import com.itheima.health.pojo.Member;
import com.itheima.health.service.MemberService;
import com.itheima.health.service.SmsService;
import com.itheima.health.vo.OrderSubmitParam;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;


/**
 * 登录控制器
 */
@RestController
@RequestMapping("/mobile/login")
@Slf4j
@Api(tags = "手机端登录接口")
public class MobileLoginController {
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private MemberService memberService;
    @Autowired
    private SmsService smsService;

    /**
     * 手机端登陆
     * @param orderSubmitParam
     * @param session
     * @return
     * @decription 手机端登陆判断。从redis 中获取生成的验证码。判断前端发送的验证码是否为null
     * 并在校验成功后，清除redis中保存的当前手机号验证码信息。
     * 并将登陆信息保存到session中，方便获取当前登陆人信息。
     */
    @PostMapping("/smsLogin")
    public Result login(@RequestBody OrderSubmitParam orderSubmitParam, HttpServletRequest session){
        log.info("当前登陆信息是"+orderSubmitParam);
        //获取生成的验证码
        boolean success = smsService.checkValidateCode("MOBILE_SIGNIN", orderSubmitParam.getTelephone(), orderSubmitParam.getValidateCode());
        if (!success) {
            return new Result(false, MessageConst.VALIDATECODE_ERROR);
        }
        Member member = new Member();
        member.setPhoneNumber(orderSubmitParam.getTelephone());
        member = memberService.createOrUpdate(member);
        session.getSession().setAttribute("member",member);
        //销毁redis中的验证码
        redisTemplate.delete(orderSubmitParam.getTelephone()+"MOBILE_SIGNIN");
        return new Result(true,MessageConst.LOGIN_SUCCESS);
    }
}
